package com.niiwoo.civet.trade.utils.koala;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AES {
    private static final Logger logger = LoggerFactory.getLogger(AES.class);


    public AES() {
    }

    public static String Encrypt(String sSrc, String sKey, String ivStr) throws Exception {
        try{
            byte[] raw = sKey.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes());
            cipher.init(1, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes());
            return (new BASE64Encoder()).encode(encrypted);
        }catch(Exception e){
            logger.error("AES Encrypt Exception",e);
            throw e;
        }
    }

    public static String Decrypt(String sSrc, String sKey, String ivStr) throws Exception {
        try {
            byte[] ex = sKey.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(ex, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes());
            cipher.init(2, skeySpec, iv);
            byte[] encrypted1 = (new BASE64Decoder()).decodeBuffer(sSrc);

            byte[] e = cipher.doFinal(encrypted1);
            String originalString = new String(e);
            return originalString;
        } catch (Exception e) {
            logger.error("AES Decrypt Exception",e);
            throw e;
        }
    }

    public static void main(String[] args) throws Exception {
        String cKey = "DSnyThrMgqDr0yXc";
        String ivStr = "0781981659016119";
        String cSrc = "{\"a\" : 233,\"b\": \"人物姓名\"}";
        System.out.println(cSrc);
        long lStart = System.currentTimeMillis();
        String enString = Encrypt(cSrc, cKey, ivStr);
        System.out.println("加密后的字串是：" + enString);
        System.out.println("加密后的字串是：" + "L9eIx4J4MITp94rXWNWImj8D73LxvavN8z5raEKRAaA=".equals(enString));
        long lUseTime = System.currentTimeMillis() - lStart;
        System.out.println("加密耗时：" + lUseTime + "毫秒");
        lStart = System.currentTimeMillis();
        String DeString = Decrypt(enString, cKey, ivStr);
        System.out.println("解密后的字串是：" + DeString);
        lUseTime = System.currentTimeMillis() - lStart;
        System.out.println("解密耗时：" + lUseTime + "毫秒");
    }
}
